package com.cheng.admin.service.order.states;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cheng.admin.constant.Constants;
import com.cheng.admin.dao.OrderMapper;
import com.cheng.admin.rabbitmq.MqConstants;
import com.cheng.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Order(Constants.ORDER_STATUS_UNSHIPPED)
@Service
@Slf4j
public class PaidState implements OrderState {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AmqpTemplate amqpTemplate;

    @Override
    public String pay(Long id) {
        throw new CustomException("已支付请勿重复支付");
    }

    @Override
    public Map<String, String> cancel(Long id) {
        throw new CustomException("已支付无法取消订单");
    }

    @Override
    public Map<String, String> ship(Long id, String logisticsNo) {
        orderMapper.update(null, Wrappers.<com.cheng.admin.model.Order>lambdaUpdate()
                .set(com.cheng.admin.model.Order::getLogisticsNo, logisticsNo)
                .set(com.cheng.admin.model.Order::getOrderStatus, Constants.ORDER_STATUS_UNCONFIRMED)
                .eq(com.cheng.admin.model.Order::getId, id));

        HashMap<String, String> result = new HashMap<>();
        result.put("result", "success");
        // 用户要是没手段确认，一段时间后会自动确认
        amqpTemplate.convertAndSend(MqConstants.DELAY_EXCHANGE_ORDER, MqConstants.DELAY_QUEUE_ORDER_CONFIRM, id,
                message -> {
                    message.getMessageProperties().setDelay(MqConstants.DELAYED_ORDER_CONFIRM_TIME);
                    return message;
                });
        return result;
    }

    @Override
    public Map<String, String> confirm(Long id) {
        throw new CustomException("未发货无法确认收货");
    }
}
